import axios, {AxiosInstance} from "axios";
import {ElMessage} from "element-plus";
import {refreshToken} from "@/api/authentication.ts";
import router from "@/router/router.ts";

const request: AxiosInstance = axios.create({
    baseURL: '/',
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json;charset=UTF-8'
    }
})


request.interceptors.request.use( (config) => {

    if (localStorage.getItem('Authorization')){
        config.headers.Authorization = localStorage.getItem('Authorization') || ''
    }

    checkTokenExpiration()

    return config
} )

request.interceptors.response.use( resp => {



    const code: number = resp.data.code

    if (code === 4396 || code === 401) {

        localStorage.removeItem('Authorization')
        sessionStorage.removeItem('isLogin')
        router.push('/login').then()

        return Promise.reject(resp.data.msg)
    }

    if (code !== 200){
        ElMessage.error(resp.data.msg)
        return Promise.reject(resp.data.msg)
    }



    return resp.data
} )


function checkTokenExpiration(){
    const threeMinute = 180000
    const dateString = localStorage.getItem("getAuthAt")
    const expireDate = new Date().getTime() + threeMinute * 10
    if (dateString && expireDate - Number.parseInt(dateString)  < threeMinute){

        refreshToken().then(res =>{
            const token = 'Bearer ' + res.data
            localStorage.setItem('Authorization', token)
            localStorage.setItem("getAuthAt", new Date().getTime().toString())
        })
    }
}

export default request